<template>
    <div class="seat-map-container">
        <!-- 图例区域 -->
        <div class="legend-container">
            <div class="legend-scroll">
                <!-- 已售座位图例 -->
                <div class="legend-item">
                    <div>
                        <img style="width:14px;height:14px"
                            src="https://gw.alicdn.com/tfscom/i2/O1CN01MoyKIm1lkYlMD0T6b_!!6000000004857-0-alipicbeacon.jpg_30x30.jpg"
                            alt="已售">
                    </div>
                    <span class="legend-text">已售</span>
                </div>

                <!-- 价格区域图例 -->
                <div v-for="(area, index) in sortedAreaData" :key="index" class="legend-item">
                    <div :class="['area-legend', `area-${index}`]" :style="{ borderColor: area.color }"></div>
                    <span class="legend-text">¥{{ area.price }}</span>
                </div>

                <!-- 不可售图例 -->
                <div class="legend-item">
                    <div class="sold-seat"></div>
                    <span class="legend-text">不可售</span>
                </div>
            </div>
        </div>

        <!-- 影厅名称 -->
        <div class="positions">
            <div><img src="../assets/index/films.png" alt="" class="file_position"></div>
            <div class="names">{{ showName }}</div>
        </div>

        <!-- 座位图主体 - 修改后的结构 -->
        <div class="seat-map-scroll-container">
            <!-- 行号标签 - 固定在左侧 -->
            <div class="row-labels">
                <div v-for="row in uniqueRows" :key="row" class="row-label">{{ row }}</div>
            </div>

            <!-- 可滚动的座位图 -->
            <div class="seat-map-wrapper" ref="seatMapWrapper">
                <div class="seat-map" ref="seatMap">
                    <!-- 中线 -->
                    <div class="center-line" :style="centerLineStyle" v-if="seat_list.length"></div>

                    <!-- 动态生成的行和列 -->
                    <div v-for="row in uniqueRows" :key="row" class="seat-row">
                        <!-- 根据column值精确放置每个座位 -->
                        <template v-for="(col) in maxColumns">
                            <div v-if="hasSeat(row, col)" class="seat-col">
                                <van-button :class="getSeatClass(row, col)" :style="getSeatStyle(row, col)"
                                    :disabled="!isSeatAvailable(row, col)" @click="handleSeatClick(row, col)"
                                    size="mini">
                                    <img v-if="!isSeatAvailable(row, col)" class="sold-seat-img"
                                        src="https://gw.alicdn.com/tfscom/i2/O1CN01MoyKIm1lkYlMD0T6b_!!6000000004857-0-alipicbeacon.jpg_30x30.jpg"
                                        alt="已售">
                                </van-button>
                            </div>
                            <!-- 没有座位的空位 -->
                            <div v-else class="empty-col"></div>
                        </template>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    props: {
        area_data: {
            type: String,
            default: ""
        },
        selectedSeats: {
            type: Array,
            default: () => []
        },
        showName: {
            type: String,
            default: "1号厅"
        },
        max_can_buy: {
            type: Number,
            default: 4
        },
        seat_list: {
            type: Array,
            default: () => []
        }
    },

    data() {
        return {
            localSelectedSeats: [],
            colors: ["#196EE2", "#ff976a", "#ee0a24", "#e485dc", "#81e67d", "#91d6f0", "#770c81", "#1c7a7a"],
            maxSeats: 5,
            selectedPerson: 0,
            autoSelectedSeats: [],
            seatStyles: {},
            sortedAreaData: [],
            seatMapHeight: 0
        };
    },

    computed: {
        uniqueRows() {
            const rows = new Set(this.seat_list.map(seat => seat.row));
            return Array.from(rows).sort((a, b) => a - b);
        },

        maxColumns() {
            return Math.max(...this.seat_list.map(seat => seat.column));
        },

        maxRows() {
            return Math.max(...this.seat_list.map(seat => seat.row));
        },

        centerLineStyle() {
            const seatWidth = 18;
            const gapWidth = 5;
            const isEvenColumns = this.maxColumns % 2 === 0;

            let centerPosition;
            if (isEvenColumns) {
                const middleRight = this.maxColumns / 2;
                centerPosition = (middleRight * seatWidth) + ((middleRight - 1) * gapWidth) + (gapWidth / 2);
            } else {
                const middle = Math.ceil(this.maxColumns / 2);
                centerPosition = (middle * seatWidth) + ((middle - 1) * gapWidth) + (gapWidth / 2);
            }

            return {
                left: `${centerPosition}px`,
                height: `${this.seatMapHeight}px`,
            };
        }
    },

    watch: {
        selectedSeats: {
            immediate: true,
            handler(newVal) {
                this.localSelectedSeats = [...newVal];
            }
        },
        area_data: {
            immediate: true,
            handler(newVal) {
                if (newVal) this.parseAndSortAreaData();
            }
        },
        uniqueRows: {
            immediate: true,
            handler() {
                this.$nextTick(() => {
                    this.calculateSeatMapHeight();
                });
            }
        }
    },

    mounted() {
        this.parseAndSortAreaData();
        this.$nextTick(() => {
            this.calculateSeatMapHeight();
        });
    },

    methods: {
        calculateSeatMapHeight() {
            if (this.$refs.seatMap) {
                const rows = this.$refs.seatMap.querySelectorAll('.seat-row');
                if (rows.length > 0) {
                    const rowHeight = rows[0].offsetHeight;
                    const rowGap = 3;
                    this.seatMapHeight = rows.length * (rowHeight + rowGap) - rowGap;
                }
            }
        },

        hasSeat(row, col) {
            return this.seat_list.some(seat => seat.row === row && seat.column === col);
        },

        parseAndSortAreaData() {
            if (!this.area_data) return;

            const areas = this.area_data.split(';').map(item => {
                const parts = item.trim().split(',');
                const areaPart = parts[0].split(':');
                const pricePart = parts[1].split(':');
                return {
                    area_id: areaPart[1],
                    price: parseFloat(pricePart[1]),
                    settle_price: parts[2] ? parseFloat(parts[2].split(':')[1]) : 0
                };
            });

            areas.sort((a, b) => a.price - b.price);
            this.sortedAreaData = areas.map((area, index) => ({
                ...area,
                color: this.colors[index % this.colors.length]
            }));
        },

        getSeatStyle(row, col) {
            const seat = this.seat_list.find(item => item.row === row && item.column === col);

            if (!this.area_data) {
                return {
                    borderColor: this.colors[0],
                    borderWidth: '1px',
                    borderStyle: 'solid'
                };
            }

            if (seat && seat.area_id) {
                const area = this.sortedAreaData.find(a => a.area_id === seat.area_id);
                if (area) {
                    return {
                        borderColor: area.color,
                        borderWidth: '1px',
                        borderStyle: 'solid'
                    };
                }
            }
            return {};
        },

        getSeatClass(row, col) {
            const seat = this.seat_list.find(item => item.row === row && item.column === col);
            if (!seat) return 'seat-button';

            let className = 'seat-button';
            const seatName = seat.seat_name;
            const isSelected = this.localSelectedSeats.includes(seatName);
            const isAutoSelected = this.autoSelectedSeats.includes(seatName);

            if (isSelected) {
                className += ' seat-selected';
            } else if (isAutoSelected) {
                className += ' seat-auto-selected';
            } else if (seat.status !== 1) {
                className += ' seat-unavailable';
            } else if (seat.area_id) {
                className += ' seat-area';
                if (!this.seatStyles[seatName]) {
                    this.$set(this.seatStyles, seatName, {
                        borderColor: this.area_data
                            ? (this.sortedAreaData.find(a => a.area_id === seat.area_id)?.color || this.colors[0])
                            : this.colors[0]
                    });
                }
            }

            return className;
        },

        handleSeatClick(row, col) {
            const seat = this.seat_list.find(item => item.row === row && item.column === col);
            if (!seat || seat.status !== 1) return;

            const seatName = seat.seat_name;
            const seatIndex = this.localSelectedSeats.indexOf(seatName);
            let newSelectedSeats = [...this.localSelectedSeats];

            if (seatIndex >= 0) {
                newSelectedSeats.splice(seatIndex, 1);
            } else {
                if (newSelectedSeats.length >= this.max_can_buy) {
                    this.$toast(`最多选择${this.max_can_buy}个座位`);
                    return;
                }
                newSelectedSeats.push(seatName);
            }

            this.localSelectedSeats = newSelectedSeats;
            this.$emit('update-selected', newSelectedSeats);
        },

        isSeatAvailable(row, col) {
            const seat = this.seat_list.find(item => item.row === row && item.column === col);
            return seat && seat.status === 1;
        },

        getSeatName(row, col) {
            const seat = this.seat_list.find(item => item.row === row && item.column === col);
            return seat ? seat.seat_name.split('排')[1] : '';
        },

        autoSelectBestSeats(num) {
            this.autoSelectedSeats = [];
            const centerRow = Math.ceil(this.maxRows / 2);
            const centerCol = Math.ceil(this.maxColumns / 2);

            for (let i = 0; i < num; i++) {
                const seat = `${centerRow}排${centerCol + i}`;
                if (this.isSeatAvailable(centerRow, centerCol + i)) {
                    this.autoSelectedSeats.push(seat);
                }
            }
        }
    }
};
</script>

<style scoped>
.seat-map-container {
    padding: 0 15px;
    text-align: center;
    border: none;
}

.legend-container {
    width: 100%;
    padding: 8px 0;
    overflow-x: auto;
    scrollbar-width: none;
    /* 隐藏 Firefox 滚动条 */
    /* scrollbar-width: thin; */
}

.legend-container::-webkit-scrollbar {
    /* height: 6px;
  border-radius: 3px; */
}

.legend-container::-webkit-scrollbar-track {
    background: transparent;
    margin: 0 12px;
}

.legend-container::-webkit-scrollbar-thumb {
    background-color: #fff;
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: 3px;
    transition: background-color 0.3s;
}

.legend-container:hover::-webkit-scrollbar-thumb,
.legend-container:active::-webkit-scrollbar-thumb {
    background-color: #ccc;
    border-color: transparent;
}

.legend-scroll {
    display: inline-flex;
    align-items: center;
    gap: 16px;
    white-space: nowrap;
    padding-bottom: 6px;
}

.legend-item {
    display: flex;
    align-items: center;
    gap: 6px;
}

.legend-item>div {
    display: flex;
    align-items: center;
}

.legend-text {
    font-size: 12px;
    color: #333;
    line-height: 1;
}

.area-legend,
.sold-seat {
    width: 14px;
    height: 14px;
    border-radius: 4px;
    flex-shrink: 0;
    background: #FFFFFF;
    border: 1px solid;
}

.sold-seat {
    border-color: #c8c9cc;
}

.positions {
    position: relative;
    margin-bottom: 65px;
    width: 100%;
    margin-top: 15px;
    text-align: center;
}

.file_position {
    width: 200px;
    height: 28px;
    position: absolute;
    left: 50%;
    top: 0;
    transform: translateX(-50%);
}

.names {
    padding: 0;
    margin: 0;
    font-family: PingFang SC;
    font-size: 12px;
    color: #797979;
    position: absolute;
    left: 50%;
    top: 18px;
    transform: translateX(-50%);
    white-space: nowrap;
}

/* 修改后的座位图容器样式 */
.seat-map-scroll-container {
    position: relative;
    display: flex;
    width: 100%;
    overflow: hidden;
}

.row-labels {
    position: sticky;
    left: 0;
    top: 0;
    z-index: 2;
    width: 20px;
    background: rgba(0, 0, 0, 0.2);
    border-radius: 20px;
    flex-shrink: 0;
}

.row-label {
    height: 24px;
    line-height: 24px;
    text-align: center;
    margin-bottom: 3px;
    font-family: PingFang SC;
    font-weight: 400;
    font-size: 10px;
    color: #FFFFFF;
}

.seat-map-wrapper {
    flex-grow: 1;
    overflow-x: auto;
    scrollbar-width: none;
    position: relative;
    margin-left: 15px;
}

.seat-map-wrapper::-webkit-scrollbar {
    display: none;
}

.seat-map {
    position: relative;
    display: flex;
    flex-direction: column;
    gap: 3px;
    width: fit-content;
    padding-left: 0;
}

.center-line {
    position: absolute;
    top: 0;
    left: 0;
    border-left: 1px dashed #ccc;
    z-index: 1;
    pointer-events: none;
    background-color: transparent;
}

.seat-row {
    display: flex;
    align-items: center;
    gap: 5px;
    position: relative;
    height: 24px;
}

.seat-col,
.empty-col {
    width: 18px;
    height: 18px;
}

.empty-col {
    visibility: hidden;
}

.seat-button {
    width: 100%;
    height: 100%;
    padding: 0;
    min-height: auto;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #FFFFFF !important;
    border: 1px solid transparent;
    font-size: 10px;
}

.seat-selected {
    background-color: #ff4444 !important;
    color: white !important;
}

.seat-auto-selected {
    background-color: #42a5f5 !important;
    color: white !important;
}

.seat-unavailable {
    background-color: #f5f5f5;
    color: #c62828;
    opacity: 0.6;
}

.sold-seat-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 2px;
}

.seat-area {
    background: #FFFFFF;
    border: 1px solid;
}
</style>